import utils.signals
from django.contrib.auth.models import User
from StartGroup.models import Group
from groupMembers.models import Member_Group, group_mem_assoc_v
from contifyuser.models import Member
import connectpeople.Constants
from datetime import datetime
from django.http import HttpResponseRedirect as redirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.paginator import Paginator
from django.utils.safestring import mark_safe
import simplejson
from django.http import HttpResponse
from operator import attrgetter
from utils import common_methods, common_query
import threading
from utils import activity_module

# Join Group
def joinGroup(request, group_web_address):
    
    # Obtain user
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Obtain group_web_address
    group_addr = group_web_address
    group_info = getGroupFromWebAddr(group_addr)
    
    mem_grp = Member_Group(group=group_info, user_id=userid, join_date=datetime.now(), group_web_address=group_addr, permission=connectpeople.Constants.regular_member)
    mem_grp.save()
    
    # Connect user to group in Graph
    activity_module.connectUserToGroup(group_addr, userid)
	
    # Force requery and skip cache
    member_data = common_query.get_member_from_gwebaddr(group_addr, True)
    common_query.get_group_member(userid, True)
    
    if common_methods.getEmailFlag(member_data[0].email_setting, connectpeople.Constants.join_group_email_flag_constant) == "1":
	#Email parameters
	# Get email ids of the user
	recipient = []
	recipient.append(member_data[0].email)
	# Compose subject for the email
	subj = group_info.group_name + " joined"
	# name of the recipeint
	rec_name = member_data[0].first_name
	
	# Send Email. Use threading
	join_group_thread= threading.Thread(target=common_methods.send_single_email_helper, kwargs={'a_sender':Group, 'a_email':recipient, 'a_name':rec_name, 'a_model':group_info, 'a_subject':subj, 'a_template':"email/groupJoinEmail.html"})
	join_group_thread.setDaemon(True)
	join_group_thread.start()
    
    return redirect("/connectpeople/group/" +group_addr)
    
# Leave Group
def leaveGroup(request, group_web_address):
    
    # Obtain user
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Obtain group_web_address
    group_addr =  group_web_address
    group_info = getGroupFromWebAddr(group_addr)
    Member_Group.objects.get(group_web_address=group_addr, user_id=userid).delete()
    
    # Force requery and skip cache
    common_query.get_member_from_gwebaddr(group_addr, True)
    common_query.get_group_member(userid, True)
    
    return redirect("/connectpeople/group/" +group_addr)

# View Members
def member_view(request, group_web_address):
    group_web_addr = group_web_address
    group = getGroupInfo(group_web_addr)
            
    # Prepare list of group members
    # Get user ids of all users associated with the group
    grp_mems = common_query.get_member_from_gwebaddr(group_web_addr, False)
        
    if request.method == 'POST':

	try:
	    action = request.POST.__getitem__('action');
	except:
	    action = None
	    
	if action == "userAccessUpdate":
	    userid = request.POST.__getitem__('userid');
	    selected = request.POST.__getitem__('selectedValue');
	    # Get Member_Group object to update
	    mem_grp = Member_Group.objects.get(user_id=userid, group_web_address=group_web_addr)
	    # Assign updated permission
	    mem_grp.permission = int(selected)
	    mem_grp.save()
	    # Refresh the cache data
	    mem_list = common_query.get_member_from_gwebaddr(group_web_addr, True)
	    # Compose return values
	    permid = "#perm_" + userid
	    permission = common_methods.getPermissionString(int(selected))
	    response = simplejson.dumps({'permid': permid, 'permission':permission})
	else:

	    # Get the sort by value and sort direction
	    sortBy = request.POST.__getitem__('sortBy')
	    sortDir = request.POST.__getitem__('sortdir')
	    if sortBy == 'name':
		if sortDir == 'asc':
		    mem_list = sorted(grp_mems, key=attrgetter('first_name'))
		else:
		    mem_list = sorted(grp_mems, key=attrgetter('first_name'), reverse=True)
	    elif sortBy == 'join':
		if sortDir == 'asc':
		    mem_list = grp_mems.reverse()
		else:
		    mem_list = grp_mems
		    
	    response = simplejson.dumps({'success': 'success'})
    else:
        mem_list = grp_mems
    
    # Define Paginator
    paginator = Paginator(mem_list, 10)

    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)

    # Get Html List of members
    #htmlList = getMembersHtml(pages)
                
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")

    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]

    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)    
        
    return render_to_response("groupMembers/member_view.html",
                              {'pages': pages, 'group':group,'permission':permission},
                              context_instance = RequestContext(request))


# Update user's permission level
def UpdateUserPermission():
    print "hi"
    
# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)
    
# Helper function to obtain grou info from group web address
def getGroupFromWebAddr(group_web_addr):
    return Group.objects.get(group_web_address=group_web_addr)
    
# Get All the members associated with the group
def getGroupMembers(group_web_addr):
    return group_mem_assoc_v.objects.filter(group_web_address = group_web_addr).order_by('-join_date')
    
# Build HTML list of members
# Building the HTMl here will help refreshing the list on server side with paginator
#def getMembersHtml(pages):
#    dataHtml = []
#
#    # Define Upper Page navigation
#    dataHtml.append("<div class='topPagination'>")
#    dataHtml.append("<div class='clearbreak noRightBreak'>")
#    if pages.has_previous:
#        dataHtml.append("<a href='?page=")
#        dataHtml.append(str(pages.previous_page_number))
#        dataHtml.append("'>previous</a>")
#    dataHtml.append("<span>Page ")
#    dataHtml.append(str(pages.number))
#    dataHtml.append(" of ")
#    dataHtml.append(str(pages.paginator.num_pages))
#    dataHtml.append("</span>")
#    if pages.has_next:
#        dataHtml.append("<a href='?page=")
#        dataHtml.append(str(pages.next_page_number))
#        dataHtml.append("'>next</a>")
#
#    dataHtml.append("</div></div>")
#
#    # Define Member List
#    dataHtml.append("<div class='nobreak memberlist'>")
#    if pages.object_list:
#	for mem in pages.object_list:
#	    dataHtml.append("<div class='nobreak singleMember'>")
#	    dataHtml.append("<div class='nobreak singleMemberPic'>")
#            try:
#		dataHtml.append("<img src='http://127.0.0.1:8000/static_media/")
#		img_path = mem.photo_path.split('media/')[1]
#		# Pull out static media path to image
#		dataHtml.append(img_path)
#	    except:
#		dataHtml.append("<img src='")
#	    
#            dataHtml.append("' class='singleMemberImg'/>")
#            dataHtml.append("</div><div class='nobreak singleMemberInfo'><div>")
#            dataHtml.append(mem.first_name)
#            dataHtml.append(" ")
#            dataHtml.append(mem.last_name)
#	    dataHtml.append("</div><div><div>Join Date: ")
#	    if mem.join_date:
#		dataHtml.append(str(datetime.date(mem.join_date)))
#	    else:
#		dataHtml.append("Creator")
#            dataHtml.append("</div></div></div></div>")
#    else:
#	dataHtml.append("<div class='nobreak'>No Members Listed</div>")
#
#    # Define Lower Page navigation
#    dataHtml.append("</div><div class='nobreak clearbreak'>")
#    if pages.has_previous:
#        dataHtml.append("<a href='?page=")
#        dataHtml.append(str(pages.previous_page_number))
#        dataHtml.append("'>previous</a>")	
#    dataHtml.append("<span>Page ")
#    dataHtml.append(str(pages.number))
#    dataHtml.append(" of ")
#    dataHtml.append(str(pages.paginator.num_pages))
#    dataHtml.append("</span>")	
#    if pages.has_next:
#        dataHtml.append("<a href='?page=")
#        dataHtml.append(str(pages.next_page_number))
#        dataHtml.append("'>next</a></div>")
#
#    return mark_safe(u''.join(dataHtml))